package com.geek.novel.utils


import android.app.Activity
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.wifi.WifiManager
import android.text.format.Formatter
import com.geek.novel.bo.AppContext
import org.json.JSONObject
import java.io.IOException
import java.io.InputStream
import java.net.*
import java.util.*


/**

 *
 *  * 功能描述: 网络连接状态监听类
 *  * 版本描述:
 *  * date: 2015-11-4
 *  * 修改描述:
 *
 */
object NetCheckTool {
    fun isNetworkAvailable(context: Context): Boolean {
        val connectivity = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (connectivity == null) {
            LogCatUtil.i("NetWorkState", "Unavailabel")
            return false
        } else {
            val info = connectivity.allNetworkInfo
            if (info != null) {
                for (i in info.indices) {
                    if (info[i].state == NetworkInfo.State.CONNECTED) {
                        LogCatUtil.i("NetWorkState", "Availabel")
                        return true
                    }
                }
            }
        }
        return false
    }

    fun getIp(): String {
        var ip = ""

        val cm = AppContext.getContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetwork = cm.activeNetworkInfo
        if (activeNetwork != null) { // connected to the internet
            if (activeNetwork.type == ConnectivityManager.TYPE_WIFI) {
                ip = getWifiIPAddress()
            } else if (activeNetwork.type == ConnectivityManager.TYPE_MOBILE) {
                ip = getMobileIPAddress()
            }
        } else {
            // not connected to the internet
        }


        return ip
    }


    private fun getWifiIPAddress(): String {
        val wifiMgr = AppContext.getContext().applicationContext.getSystemService(Activity.WIFI_SERVICE) as WifiManager
        val wifiInfo = wifiMgr.connectionInfo
        val ip = wifiInfo.ipAddress
        return Formatter.formatIpAddress(ip)
    }

    private fun getMobileIPAddress(): String {
        var ip = ""
        try {
            val en = NetworkInterface
                    .getNetworkInterfaces()
            while (en.hasMoreElements()) {
                val intf = en.nextElement()
                val enumIpAddr = intf
                        .inetAddresses
                while (enumIpAddr.hasMoreElements()) {
                    val inetAddress = enumIpAddr.nextElement()
                    if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                        ip = inetAddress.getHostAddress()
                        if (CommUtil.isNull(ip)) {
                            val interfaces = Collections.list(NetworkInterface.getNetworkInterfaces())
                            interfaces
                                    .map { Collections.list(it.inetAddresses) }
                                    .flatMap { it }
                                    .filterNot { it.isLoopbackAddress }
                                    .forEach { ip = it.hostAddress }
                        }
                        return ip
                    }
                }
            }
        } catch (ex: Exception) {
            return ip
        }
        return ip


    }

    /**
     * 获取公网ip(要访问Url，要放到后台线程里处理)
     *
     * @return
     */
    fun getNetIp(): String? {
        val infoUrl: URL
        val inStream: InputStream
        var line = ""
        try {
            infoUrl = URL("http://pv.sohu.com/cityjson?ie=utf-8")
            val connection = infoUrl.openConnection()
            val httpConnection = connection as HttpURLConnection
            val responseCode = httpConnection.responseCode
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.inputStream


                line = inStream.bufferedReader().use { it.readText() }

                inStream.close()
                // 从反馈的结果中提取出IP地址
                val start = line.indexOf("{")
                val end = line.indexOf("}")
                val json = line.substring(start, end + 1)

                val jsonObject = JSONObject(json)
                line = jsonObject.optString("cip")


            }
        } catch (e: MalformedURLException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return line

    }

    val isNetworkOnline: Boolean
        get() {
            val runtime = Runtime.getRuntime()
            try {
                val ipProcess: Process
                ipProcess = runtime.exec("ping -c 1 https://www.baidu.com/")
                val exitValue = ipProcess.waitFor()
                return exitValue == 0
            } catch (e: IOException) {
                e.printStackTrace()
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }

            return false
        }
}
